import { ref, watch } from 'vue'
import Configuration from '@/api/client/configuration.js'
import message from 'ant-design-vue/lib/message/index.js'
import { SAVED_SUCCESSFULLY } from '@/constants/message.js'

export function useSatisfactionSurvey(id) {
  const satisfactionSurveyLoading = ref(true)
  const satisfactionSurveyEnabled = ref(false)
  const satisfactionSurveyMonth = ref(1)
  const satisfactionSurveyMonthTemp = ref(1)
  const showSatisfactionSurveyMonthDialog = ref(false)
  const getSatisfactionSurveyStatus = () => {
    Configuration.getSatisfactionSurveyStatus(id)
      .then(({ data }) => {
        satisfactionSurveyEnabled.value = data.surveySwitch
        satisfactionSurveyMonth.value = data.surveyMonth
      })
      .finally(() => {
        satisfactionSurveyLoading.value = false
      })
  }
  watch(
    () => showSatisfactionSurveyMonthDialog.value,
    () => {
      satisfactionSurveyMonthTemp.value = satisfactionSurveyMonth.value
    }
  )
  getSatisfactionSurveyStatus()
  const handleChangeSatisfactionSurvey = (onlySaveMonth = false) => {
    // 只保存月份，不改变状态
    const status = onlySaveMonth ? satisfactionSurveyEnabled.value : !satisfactionSurveyEnabled.value
    Configuration.saveSatisfactionSurveyStatus(id, status, satisfactionSurveyMonthTemp.value).then(() => {
      message.success(SAVED_SUCCESSFULLY)
      getSatisfactionSurveyStatus()
      showSatisfactionSurveyMonthDialog.value = false
    })
  }
  return {
    satisfactionSurveyEnabled,
    satisfactionSurveyMonth,
    satisfactionSurveyMonthTemp,
    showSatisfactionSurveyMonthDialog,
    satisfactionSurveyLoading,
    handleChangeSatisfactionSurvey
  }
}
